package com.sinry.api.aggregation.messagers;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.json.JSONUtil;
import com.sinry.api.aggregation.entity.ApiRegister;
import com.sinry.api.aggregation.service.ApiRegisterService;
import com.sinry.common.core.domain.dto.ApiRegisterDto;
import com.sinry.message.constant.QueueConst;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.Optional;

/**
 * @author linxinlei
 * @project sinry-cloud
 * @description Swagger消息消费者实现
 * @date 2022/5/29
 **/
@Slf4j
@Component
public class SwaggerMessageConsumer {

    private final ApiRegisterService apiRegisterService;

    @Autowired
    public SwaggerMessageConsumer(ApiRegisterService apiRegisterService) {
        this.apiRegisterService = apiRegisterService;
    }

    @RabbitListener(queues = QueueConst.SWAGGER_AUTO_REPORT)
    public void monitor(ApiRegisterDto data) {
        // 消息接收
        log.info("监听到API上报：{}", JSONUtil.toJsonStr(data));
        if (!StringUtils.hasText(data.getServiceName())) {
            return;
        }
        ApiRegister findOne = apiRegisterService.lambdaQuery()
                .eq(ApiRegister::getServiceName, data.getServiceName()).one();
        ApiRegister apiRegister = Optional.ofNullable(findOne).orElse(new ApiRegister());
        BeanUtil.copyProperties(data, apiRegister, CopyOptions.create().ignoreNullValue());
        apiRegisterService.saveOrUpdate(apiRegister);
    }
}
